import java.awt.*; 

public class FigureCanvas extends Canvas implements Runnable {
	Image offscreen;
        Figure shape;
	int imagewidth = 200, imageheight = 100; // The canvas sizes.
	Thread animator = null;  // This thread will run this object.
	boolean please_stop = false;  // We only request a stop in case we are mid-draw.
	long startTime; // A guess at when we want the next redraw to begin.

	FigureCanvas() {
		imagewidth = 200; imageheight = 100;
		shape = new Figure(imagewidth,imageheight,0.0,0.0);
	}

	public void setVelocity(double velocity) {
		shape.setVelocity(velocity);
	}

	public void setPosition(double pos) {
		shape.setPosition(pos);
	}

	// These two inform the layout what our minimum requirements are.
	// Without these, you may get a zero size object.
	public Dimension getPreferredSize() {
		Dimension d = new Dimension(150,50);
		return d;
	}

	public Dimension getMinimumSize() {
		Dimension d = new Dimension(150,50);
		return d;
	}

	// Start the animation
	public void enable() {
		super.enable();
		// Start the thread.
        	animator = new Thread(this);
        	animator.start();
		repaint();
	}

	// Stop it.
	public void disable() { 
        	if (animator != null) animator.stop();
        	animator = null;
		super.disable();
	}

	// This method draws the background and  text at its current position.
	public void paint(Graphics g) {
        	update(g);
	}


	public void update( Graphics g ) {
		if (offscreen != null) {
	            g = this.getGraphics();
        	    g.drawImage(offscreen, 0, 0, this);
		} else {
		    g.clearRect(0,0,imagewidth,imageheight);
		}
	}

    public boolean mouseDown(Event e, int x, int y) {
	if (e.target==this) {
		toggle();
	}
        return true;
    }


    public void toggle() {
        // if running, stop it.  Otherwise, start it.
        if (animator != null) please_stop = true;
        else { please_stop = false; enable(); } 
    }

    public void run() {
        while(!please_stop) {
            Dimension d = this.size();
            
            // Make sure the offscreen image is created and is the right size.
            if ((offscreen == null) ||
                ((imagewidth != d.width) || (imageheight != d.height))) {
		if (d.width>1 && d.height>1) {
	                imagewidth = d.width;
        	        imageheight = d.height;
		}
                offscreen = createImage(imagewidth, imageheight);
		shape.setSize(imagewidth,imageheight);
            }
           
            Graphics g = offscreen.getGraphics();
	    g.clearRect(0,0,d.width,d.height);
	    shape.draw(g);
	    repaint();
	    for (int j=1;j<1000000;j++);
        }
        animator = null;
    }
}
